<template>
  <div class="reviews-container">
    <div class="page-header">
      <h2>评价管理</h2>
    </div>

    <el-card class="reviews-card">
      <el-table :data="reviews" v-loading="loading" style="width: 100%">
        <el-table-column label="用户" width="120">
          <template #default="{ row }">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column label="菜品信息" min-width="200">
          <template #default="{ row }">
            <div class="dish-info">
              <img :src="row.Dish?.image_url || '/default-dish.jpg'" class="dish-image">
              <span class="dish-name">{{ row.Dish?.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="评分" width="150">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled />
          </template>
        </el-table-column>

        <el-table-column label="评价内容" min-width="200">
          <template #default="{ row }">
            <el-text class="content-preview">
              {{ row.content.length > 20 ? row.content.slice(0, 20) + '...' : row.content }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="评价图片" width="150">
          <template #default="{ row }">
            <el-image-group v-if="row.images?.length">
              <el-image
                v-for="img in row.images"
                :key="img"
                :src="img"
                :preview-src-list="row.images"
                style="width: 50px; height: 50px; margin-right: 5px"
                fit="cover"
              />
            </el-image-group>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="评价时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="商家回复" min-width="200">
          <template #default="{ row }">
            <div class="reply-status">
              <el-tag 
                :type="row.reply ? 'success' : 'info'" 
                effect="light" 
                size="small"
              >
                {{ row.reply ? '已回复' : '待回复' }}
              </el-tag>
              <el-button 
                type="primary" 
                link
                @click="showDetailDialog(row)"
              >
                查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评价详情"
      width="600px"
    >
      <div class="review-detail">
        <div class="detail-item">
          <label>用户：</label>
          <span>{{ currentReview?.username }}</span>
        </div>
        
        <div class="detail-item">
          <label>菜品：</label>
          <span>{{ currentReview?.Dish?.name }}</span>
        </div>
        
        <div class="detail-item">
          <label>评分：</label>
          <el-rate :model-value="currentReview?.rating || 0" disabled />
        </div>
        
        <div class="detail-item">
          <label>评价内容：</label>
          <p class="content-full">{{ currentReview?.content }}</p>
        </div>
        
        <div class="detail-item" v-if="currentReview?.images?.length">
          <label>评价图片：</label>
          <div class="images-container">
            <el-image
              v-for="img in currentReview.images"
              :key="img"
              :src="img"
              :preview-src-list="currentReview.images"
              style="width: 100px; height: 100px; margin-right: 10px"
              fit="cover"
            />
          </div>
        </div>
        
        <div class="detail-item">
          <label>评价时间：</label>
          <span>{{ formatDate(currentReview?.created_at) }}</span>
        </div>
        
        <div class="reply-section">
          <h4>商家回复</h4>
          <template v-if="currentReview?.reply">
            <p class="reply-content">{{ currentReview.reply }}</p>
          </template>
          <template v-else>
            <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
            <div class="reply-actions">
              <el-button type="primary" @click="submitReply">提交回复</el-button>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const reviews = ref([])
const detailDialogVisible = ref(false)
const currentReview = ref<any>(null)
const replyForm = ref({
  reply: ''
})

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取评价列表
const loadReviews = async () => {
  loading.value = true
  try {
    const response = await fetch(
      `http://localhost:8080/api/admin/reviews?page=${currentPage.value}&pageSize=${pageSize.value}`,
      {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      }
    )
    const data = await response.json()
    if (response.ok) {
      reviews.value = data.reviews
      total.value = data.total
    }
  } catch (error) {
    console.error('Load reviews error:', error)
    ElMessage.error('加载评价失败')
  } finally {
    loading.value = false
  }
}

// 显示详情对话框
const showDetailDialog = (review: any) => {
  currentReview.value = review
  replyForm.value.reply = ''
  detailDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!currentReview.value) return
  if (!replyForm.value.reply.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    const response = await fetch(`http://localhost:8080/api/admin/reviews/${currentReview.value.id}/reply`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        reply: replyForm.value.reply
      })
    })

    if (!response.ok) throw new Error('回复失败')
    
    ElMessage.success('回复成功')
    detailDialogVisible.value = false
    loadReviews() // 刷新评价列表
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '回复失败')
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadReviews()
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  loadReviews()
}

onMounted(() => {
  loadReviews()
})
</script>

<style scoped>
.reviews-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.reviews-card {
  margin-bottom: 20px;
}

.dish-info {
  display: flex;
  align-items: center;
}

.dish-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.dish-name {
  font-size: 14px;
  color: #303133;
}

.reply-content {
  color: #606266;
  font-size: 14px;
}

.review-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  display: block;
  margin-bottom: 8px;
}

.content-full {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #303133;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.content-preview {
  color: #606266;
}

.reply-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.reply-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.reply-content {
  color: #606266;
  line-height: 1.6;
}

.reply-actions {
  margin-top: 15px;
  text-align: right;
}

.reply-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.reply-status .el-tag {
  min-width: 56px;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 